<template>
  <MeModal ref="modalRef" width="500px">
    <n-form
      ref="modalFormRef"
      label-placement="left"
      require-mark-placement="left"
      :label-width="130"
      :model="modalForm"
    >
      <n-form-item label="组名称（中午）" path="name" :rule="required">
        <n-input v-model:value="modalForm.name" placeholder="请输入组名称（中文）" />
      </n-form-item>
      <n-form-item label="组标识（英文）" path="code" :rule="required">
        <n-input v-model:value="modalForm.code" placeholder="请输入组标识（英文）" />
      </n-form-item>
      <n-form-item label="备注" path="remark">
        <n-input v-model:value="modalForm.remark" type="textarea" placeholder="请输入备注" />
      </n-form-item>
    </n-form>
  </MeModal>
</template>

<script setup>
import { MeModal } from '@/components/index.js'
import { useForm, useModal } from '@/composables'

import api from '../api.js'

const emit = defineEmits(['refresh'])
const [modalFormRef, modalForm, validation] = useForm()
const [modalRef, okLoading] = useModal()

const required = {
  required: true,
  message: '此为必填项',
  trigger: ['blur', 'change'],
}

const modalAction = ref('')

function handleOpen(options = {}) {
  const { action, row = {}, ...rest } = options
  modalAction.value = action
  modalForm.value = { ...row }
  modalRef.value.open({ ...rest, onOk: onSave })
}

async function onSave() {
  await validation()
  okLoading.value = true
  try {
    let res
    if (modalAction.value === 'add') {
      res = await api.createConfigGroup(modalForm.value)
    }
    else if (modalAction.value === 'edit') {
      res = await api.updateConfigGroup(modalForm.value)
    }
    $message.success(res.message)
    emit('refresh')
  }
  finally {
    okLoading.value = false
  }
}

defineExpose({
  handleOpen,
})
</script>
